package logic

import (
	"context"
	"errors"
	"novel-world/model/cache"
	"novel-world/model/mysql"

	"novel-world/novelrpc/internal/svc"
	"novel-world/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *novelrpc.UpdatePasswordRequest) (*novelrpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	if err := user.PasswordFirst(mysql.DB, in.Mobile); err != nil {
		return nil, errors.New("用户不存在")
	}
	data := mysql.User{
		Mobile:   user.Mobile,
		Password: in.Password,
	}
	if err := data.UpdatePassword(mysql.DB, in.Mobile); err != nil {
		return nil, errors.New("密码重置失败")
	}
	result, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.Mobile).Result()
	if result != in.SendSmsEnd {
		return nil, errors.New("验证码错误")
	}
	return &novelrpc.UpdatePasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
